package com.yaodian100.mall.mobilexml;

import java.io.StringWriter;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.announcement.entity.Announcement;
import com.yaodian100.ec.announcement.service.AnnouncementService;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.image.entity.Image;
import com.yaodian100.ec.image.service.ImageService;
import com.yaodian100.ec.member.entity.ImageValid;
import com.yaodian100.ec.member.entity.LoginHistory;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.entity.ViewWishList;
import com.yaodian100.ec.member.entity.WishList;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.Specification;
import com.yaodian100.ec.product.entity.SpecificationInventory;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.search.Doc;
import com.yaodian100.ec.search.SearchResult;
import com.yaodian100.ec.search.entity.Keyword;
import com.yaodian100.ec.shelf.entity.Shelf;
import com.yaodian100.ec.shelf.service.ShelfService;
import com.yaodian100.ec.shopping.entity.CartOrderProduct;
import com.yaodian100.ec.shopping.entity.CartOrderProductDetail;
import com.yaodian100.ec.shopping.entity.CartOrders;
import com.yaodian100.ec.shopping.service.CartOrdersService;
import com.yaodian100.ec.timelimitsale.entity.TimeLimitMain;
import com.yaodian100.ec.timelimitsale.entity.TimeLimitProd;
import com.yaodian100.ec.timelimitsale.service.TimeLimitSaleService;
import com.yaodian100.mall.member.util.UserData;
import com.yaodian100.mall.search.web.SearchAction;

//import java.net.URLEncoder;

public class MobileAction extends SearchAction { // ActionSupport

	@Autowired
	private ProductService productService;
	@Autowired
	private AnnouncementService announcementService;
	@Autowired
	private ProductService productservice;
	@Autowired
	private ImageService imageservice;
	@Autowired
	private TimeLimitSaleService timeLimitSaleService;

	// private KeywordService keywordService;

	@Resource
	private CategoryService categoryService;
	@Resource
	private CartOrdersService cartOrdersService;
	@Resource
	private MemberService memberService;
	@Resource
	private ShelfService shelfService;
	@Resource
	private BaseManager baseMgr;
	private List<ViewWishList> viewWishList;
	@Autowired
	private TemplateService templateService;

	private String XML_Result;

	private Product product;
	private Shelf shelf;
	private long announcementSize;
	private List<Announcement> announcementList;
	private SimplePager pager;
	private String orderByDate = "desc";
	private final Logger logger = LoggerFactory.getLogger(MobileAction.class);
	private String loginresult;

	// member log in process
	private String loginID;
	private String pwd;
	private Member member;
	private String mobile;

	private int errTimes;
	private String mail;
	private String ccode;
	private String actionResult;

	// wishlist process
	private String wishListId;
	private String productId;
	private String productPrice;
	private String delIdList;

	// Shopping Cart
	private CartOrders cartOrders;
	private Map<String, String> resultMap;
	private List<CartOrderProductDetail> cartOrderProductDetailList;
	private List<CartOrderProduct> cartOrderProductList;
	// private CartOrderProduct cartOrderProduct;
	private List<String> tlpList;
	private String tlpCode;// 限時搶購回傳代碼
	private String addOns;
	private String[] itemNo;
	private String[] specNo;
	private String[] qty;
	private String[] categoryPath;
	private String[] ptype;
	private String cmpUuid;// 滿額購uuid
	private String delCartProdId;
	private String cartId;

	/**
	 * 
	 */
	private static final long serialVersionUID = -5603644938339330121L;

	public String timelimitsalelist() throws Exception {
		DateFormat df = new SimpleDateFormat("yyyyMMdd");
		DateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String checkShelf = null;
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		Calendar cld = Calendar.getInstance();
		Date dtu = cld.getTime();
		String date = (request.getParameter("date") != null ? request.getParameter("date") : df2.format(dtu));
		// System.out.println(date);
		// ----------------------------------
		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_product;
		Element x_product_id;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);
		try {
			Date time = df.parse(StringUtils.substring(date, 0, 8));
			Date genTime = df2.parse(date);
			CommonCriteria criteria = new CommonCriteria();
			criteria.addEq("saleDate", time);
			criteria.addEq("categoryID", 0);
			List<TimeLimitMain> tlmList = timeLimitSaleService.getList(0, -1, criteria, null);
			if (null == tlmList || tlmList.isEmpty()) {
				x_dataset.addElement("result").setText("fail");
				x_dataset.addElement("reason").setText("无秒杀活动");
				// return null;
			} else {

				criteria = new CommonCriteria();
				criteria.addEq("mainId", tlmList.get(0).getId());
				List<TimeLimitProd> tlpList = timeLimitSaleService.getTimeLimitProdList(criteria,
						new String[] { "startDate asc" }, 0, -1);
				if (null == tlpList || tlpList.isEmpty()) {
					x_dataset.addElement("result").setText("fail");
					x_dataset.addElement("reason").setText("秒杀活动无商品");
					// return null;
				} else {
					// System.out.println(tlpList.size());

					// 检查库存 & 结束时间
					Map<String, String> qtyMap = new HashMap<String, String>();
					Map<String, String> prodTypeMap = new HashMap<String, String>();
					List<String> errProd = new ArrayList<String>();
					// Map<String, Date> endTimeMap = new HashMap<String, Date>();
					for (int i = 0; i < tlpList.size(); i++) {
						TimeLimitProd tlp = tlpList.get(i);
						tlp.setTmpEndDate(tlp.getEndDate());
						if ((i < tlpList.size() - 1) && tlpList.get(i + 1).getIsRepeat().equals("Y")) {
							i++;
							for (int j = i; j < tlpList.size(); j++) {
								if (tlpList.get(j).getIsRepeat().equals("Y")) {
									tlp.setTmpEndDate(tlpList.get(j).getEndDate());
								} else {
									i = j - 1;
									break;
								}
							}
						}
						if (tlp.getIsRepeat().equals("N") && (!qtyMap.containsKey(tlp.getProductId()))) {
							int qty = 0;
							Map<String, SpecificationInventory> smap = productService
									.getSpecificationInventoryMap(tlp.getProductId());
							if (!smap.isEmpty()) {
								Set<String> key = smap.keySet();
								for (Iterator<String> it = key.iterator(); it.hasNext();) {
									String name = it.next();
									SpecificationInventory sp = smap.get(name);
									qty += (sp.getAvailableInventory() - sp.getSoldInventory() + sp.getCancelInventory());
								}
								qtyMap.put(tlp.getProductId(), Integer.toString(qty));

								// 发信资讯
								Product p = productService.get(tlp.getProductId());
								if (tlp.getStartDate().getTime() > genTime.getTime()
										&& (qty == 0 || ("Y".equals(p.getIsDelete()) || "H".equals(p.getIsDelete())))) {
									errProd.add(tlp.getProductId());
									prodTypeMap.put(tlp.getProductId(), p.getIsDelete());
								}
								// 抢购中商品
								if (tlp.getStartDate().getTime() <= genTime.getTime()
										&& tlp.getTmpEndDate().getTime() > genTime.getTime()) {
									Shelf s = shelfService.getActiveShelfByProductId(tlp.getProductId());
									if (null == s) {
										checkShelf = "秒杀中商品:" + tlp.getProductId() + " 未上架";
									} else if (s.getShelfPrice().compareTo(tlp.getLimitPrice()) != 0) {
										checkShelf = "秒杀中商品:" + tlp.getProductId() + " 秒杀价:" + tlp.getLimitPrice() + " 卖场价格:"
												+ s.getShelfPrice();
									}
								}
							}
						}
					}
					// System.out.println(ServerValue.getFrontContextPath());
					// System.out.println(qtyMap.toString());
					// System.out.println(genTime.toString());
					CommonCriteria crit = new CommonCriteria();
					for (TimeLimitProd tp : tlpList) {
						// System.out.println(tp.getProductName());

						x_product = x_dataset.addElement("product");
						x_product_id = x_product.addElement("product_id").addText(tp.getProductId());
						x_product_id = x_product.addElement("product_name").addText(tp.getProductName());
						// x_product_id =
						// x_product.addElement("image").addText("http://sitecmall.yaodian100.com/PImg/0000/"+doc.getProductId()+"/"+doc.getProductId()+"_m135.jpg");
						x_product_id = x_product.addElement("limit_price").addText(String.valueOf(tp.getLimitPrice()));
						x_product_id = x_product.addElement("member_price").addText(String.valueOf(tp.getMemberPrice()));
						x_product_id = x_product.addElement("start_date").addText(String.valueOf(tp.getStartDate()));
						x_product_id = x_product.addElement("end_date").addText(String.valueOf(tp.getEndDate()));
						if (qtyMap.get(tp.getProductId()) != null) {
							x_product_id = x_product.addElement("qty").addText(String.valueOf(qtyMap.get(tp.getProductId())));
						} else {
							x_product_id = x_product.addElement("qty").addText("");
						}
						crit.addEq("productId", tp.getProductId());
						crit.addEq("type", "MAIN");
						crit.addEq("isDelete", "N");
						List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });
						int b1 = 0;
						int b2 = 0;
						for (Image img : images) {
							if (img.getImgFilePath().indexOf("_m75") != -1) {
								x_product_id = x_product.addElement("image_s_path").addText(img.getImgFilePath());
								b1 = 1;
							} else if (img.getImgFilePath().indexOf("_m135") != -1) {
								x_product_id = x_product.addElement("image_l_path").addText(img.getImgFilePath());
								b2 = 1;
							}
						}
						if (b1 == 0) {
							x_product_id = x_product.addElement("image_s_path").addText("");
						}
						if (b2 == 0) {
							x_product_id = x_product.addElement("image_l_path").addText("");
						}
					}
					x_dataset.addElement("genTime").setText(date);
					x_dataset.addElement("result").setText("success");
					x_dataset.addElement("reason").setText("执行完成");
				}
			}

		} catch (Exception e) {
			x_dataset.addElement("result").setText("error");
			x_dataset.addElement("reason").setText("系统内部错误");
			System.out.println("***" + e.toString());
			logger.info("MobileAction_product error :{}", e.toString());
		}
		writer.write(document);
		writer.flush();
		writer.close();
		System.out.println(out.toString());
		setXML_Result(out.toString());
		return "finish";
	}

	// / call method: mobilexml/productlist.do?searchKeyword=%25E7%25A7%2592%25E6%259D%2580&start=1&limit=10&totalPage=2
	public String productlist() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		String ltype = request.getParameter("ltype");
		String p_start = (request.getParameter("start") != null ? request.getParameter("start") : "0");
		String p_limit = (request.getParameter("limit") != null ? request.getParameter("limit") : "10");
		int p_start_v = Integer.valueOf(p_start).intValue();
		int p_limit_v = Integer.valueOf(p_limit).intValue();
		// ----------------------------------
		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_product;
		Element x_product_id;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);

		// System.out.println("秒杀="+JspUtil.urlEncoding("秒杀" , "UTF-8"));
		// System.out.println("立减="+JspUtil.urlEncoding("立减" , "UTF-8"));
		// System.out.println("优惠="+JspUtil.urlEncoding("优惠" , "UTF-8"));
		// System.out.println("流行="+JspUtil.urlEncoding("流行" , "UTF-8"));
		try {
			System.out.println(getSearchKeyword());
			System.out.println(p_start_v);
			System.out.println(p_limit_v);
			setSearchWithBrief("0");
			setSearchWithDescription("0");
			setFuzzySearch(null);
			setZ("0");
			// setpIndex(p_start);
			pager.setCurrentPage(p_start_v);

			setPager(pager);

			setPageSize(p_limit_v);

			// setPagesize("40"); // 此方法沒定義
			String sh = search();
			SearchResult srt = getResult1();
			Doc[] ld = srt.getDocs();

			CommonCriteria crit = new CommonCriteria();
			if (srt.docs.length > 0) {
				x_dataset.addElement("total_size").setText(String.valueOf(srt.getTotal()));
				int n_size = (srt.docs.length > p_limit_v ? p_limit_v : srt.docs.length);
				for (int a = 0; a < n_size; a++) {
					Doc doc = srt.docs[a];
					x_product = x_dataset.addElement("product");
					x_product_id = x_product.addElement("product_id").addText(doc.getProductId());
					x_product_id = x_product.addElement("product_name").addText(doc.getProductName());
					// x_product_id =
					// x_product.addElement("image").addText("http://sitecmall.yaodian100.com/PImg/0000/"+doc.getProductId()+"/"+doc.getProductId()+"_m135.jpg");
					x_product_id = x_product.addElement("list_price").addText(String.valueOf(doc.getListPrice()));
					x_product_id = x_product.addElement("shelf_price").addText(String.valueOf(doc.getShelfPrice()));

					crit.addEq("productId", doc.getProductId());
					crit.addEq("type", "MAIN");
					crit.addEq("isDelete", "N");
					List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });
					int b1 = 0;
					int b2 = 0;
					for (Image img : images) {
						if (img.getImgFilePath().indexOf("_m75") != -1) {
							x_product_id = x_product.addElement("image_s_path").addText(img.getImgFilePath());
							b1 = 1;
						} else if (img.getImgFilePath().indexOf("_m135") != -1) {
							x_product_id = x_product.addElement("image_l_path").addText(img.getImgFilePath());
							b2 = 1;
						}
					}
					if (b1 == 0) {
						x_product_id = x_product.addElement("image_s_path").addText("");
					}
					if (b2 == 0) {
						x_product_id = x_product.addElement("image_l_path").addText("");
					}

				}
			}
			x_dataset.addElement("result").setText("success");
			x_dataset.addElement("reason").setText("系统執行成功");
		} catch (Exception ex) {
			x_dataset.addElement("result").setText("error");
			x_dataset.addElement("reason").setText("系统内部错误:" + ex.toString());
			// System.out.println("***"+ex.toString());
			logger.info("MobileAction_product error :{}", ex.toString());
		}
		writer.write(document);
		writer.flush();
		writer.close();
		System.out.println(out.toString());
		setXML_Result(out.toString());
		return "finish";

	}

	public String product() throws Exception {
		// 開始組XML物件
		// ----------------------------------
		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_product;
		Element x_product_id;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);
		try {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			String p_productid = request.getParameter("productid");
			String p_limit = request.getParameter("limit");

			System.out.println("###" + p_productid);

			// 取得文檔資料
			shelf = shelfService.getActiveShelfByProductId(p_productid);
			String outSaleType = "";
			Product product = productservice.get(p_productid);
			// MAIN("0"), PREBUY("1"), PRESENT("2"), ADDON("3"), EVENT("4"), QUOTAFILLED("5"), NPICKM("6"), HIGHEND("7")
			if (product != null) {

				int qty = 0;
				Map<String, SpecificationInventory> smap = productService.getSpecificationInventoryMap(p_productid);
				if (!smap.isEmpty()) {
					Set<String> key = smap.keySet();
					for (Iterator<String> it = key.iterator(); it.hasNext();) {
						String name = it.next();
						System.out.println("### --->:" + name);
						SpecificationInventory sp = smap.get(name);
						qty += (sp.getAvailableInventory() - sp.getSoldInventory() + sp.getCancelInventory());
					}
				}
				System.out.println("total_inventory:" + qty);
				if (qty == 0) { // 无库存
					x_dataset.addElement("result").setText("fail");
					x_dataset.addElement("reason").setText("商品已无库存");
				} else if (product.getProductType() == 6) { // N选M 商品先排除在外
					x_dataset.addElement("result").setText("fail");
					x_dataset.addElement("reason").setText("此商品未开放订购");
				} else if (product.getIsDelete().equals("H") || product.getIsDelete().equals("Y") || this.shelf == null
						|| product.getProductType() == 2 || product.getProductType() == 3) {
					/*
					 * outSaleType = "0"; if (product.getProductType() == 2 || product.getProductType() == 3) { outSaleType = "1";
					 * } else { outSaleType = "0"; } System.out.println("### outSaleType:"+outSaleType);
					 */
					x_dataset.addElement("result").setText("fail");
					x_dataset.addElement("reason").setText("商品不明原因未上架");
				} else {

					String productdetails = productservice.readFromFile(p_productid, "details");
					String productdescs = productservice.readFromFile(p_productid, "description");
					String productbrief = productservice.readFromFile(p_productid, "brief");
					String productordernotice = productservice.readFromFile(p_productid, "orderNotice");

					if (product != null) {
						x_product = x_dataset.addElement("product");
						x_product_id = x_product.addElement("product_id").addText(product.getProductId());
						x_product_id = x_product.addElement("product_name").addText(
								(product.getProductName() != null ? product.getProductName() : ""));
						x_product_id = x_product.addElement("product_desc").addText(
								(product.getProductDescription() != null ? product.getProductDescription() : ""));
						x_product_id = x_product.addElement("product_detail").addText(
								(product.getProductDetails() != null ? product.getProductDetails() : ""));
						x_product_id = x_product.addElement("product_brief").addText(
								(product.getProductBrief() != null ? product.getProductBrief() : ""));
						x_product_id = x_product.addElement("product_text_desc").addCDATA(productdescs);
						x_product_id = x_product.addElement("product_text_details").addCDATA(productdetails);
						x_product_id = x_product.addElement("product_text_brief").addCDATA(productbrief);
						x_product_id = x_product.addElement("product_text_ordernotice").addCDATA(productordernotice);
						x_product_id = x_product.addElement("product_keyword").addText(
								(product.getProductKeyword() != null ? product.getProductKeyword() : ""));
						x_product_id = x_product.addElement("product_brand").addText(
								(product.getProductBrand() != null ? product.getProductBrand() : ""));
						x_product_id = x_product.addElement("category_path").addText(
								(product.getCategory().getCategoryPath() != null ? product.getCategory().getCategoryPath() : ""));
						// x_product_id = x_product.addElement("product_memo").addText(product.getProductMemo()); // 會出現null
						x_product_id = x_product.addElement("product_type").addText(String.valueOf(product.getProductType()));
						x_product_id = x_product.addElement("product_weight").addText(String.valueOf(product.getProductWeight()));
						x_product_id = x_product.addElement("product_width").addText(String.valueOf(product.getProductWidth()));
						x_product_id = x_product.addElement("list_price").addText(String.valueOf(product.getListPrice()));
						x_product_id = x_product.addElement("pd_shelf_price").addText(String.valueOf(product.getPrpsShelfPrice()));
						if (shelf != null) {
							x_product_id = x_product.addElement("shelf_price").addText(String.valueOf(shelf.getShelfPrice()));
						} else {
							x_product_id = x_product.addElement("shelf_price").addText(String.valueOf(product.getPrpsShelfPrice()));
							// x_product_id = x_product.addElement("brand").addText(product.getProductBrand());
						}

						CommonCriteria crit = new CommonCriteria();
						List<Specification> spclist = product.getSpecifications();
						String spv = "";
						String spn = "";
						String spq = "";
						String spt = "";
						if (spclist.size() != 0) {
							Integer inventory = 0;
							for (int a = 0; a < spclist.size(); a++) {
								// for (Specification spc : spclist) {
								Specification spc = spclist.get(a);

								String hql = "from SpecificationInventory where specId=?";
								SpecificationInventory si = (SpecificationInventory) baseMgr.queryByHql(hql, new Object[] { spc
										.getSpecificationId() }, 0, 1)[0];
								inventory = si.getInventory();

								// System.out.println("### inventory:"+spc.getSpecificationId());
								// SpecificationInventory sp = smap.get(spc.getSpecificationId());
								// int gp = sp.getAvailableInventory() - sp.getSoldInventory() + sp.getCancelInventory();
								spv += spc.getSpecificationName();
								spn += spc.getSpecificationId();
								spq += String.valueOf(inventory);
								spt += spc.getMinCountPerOrder();
								if (a < spclist.size() - 1) {
									spv += ",";
								}
								if (a < spclist.size() - 1) {
									spn += ",";
								}
								if (a < spclist.size() - 1) {
									spq += ",";
								}
								if (a < spclist.size() - 1) {
									spt += ",";
								}
							}
						}
						x_product_id = x_product.addElement("specification_id").addText(spn);
						x_product_id = x_product.addElement("specification_name").addText(spv);
						x_product_id = x_product.addElement("specification_inventory").addText(spq);
						x_product_id = x_product.addElement("specification_MinCountPerOrder").addText(spt);

						crit.addEq("productId", product.getProductId());
						crit.addEq("type", "MAIN");
						crit.addEq("isDelete", "N");
						List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });
						int b1 = 0;
						for (Image img : images) {
							if (img.getImgFilePath().indexOf("_m500") != -1) {
								x_product_id = x_product.addElement("image_path").addText(img.getImgFilePath());
								b1 = 1;
							}
						}
						if (b1 == 0) {
							x_product_id = x_product.addElement("image_path").addText("");
						}
					}
				}
			} else {
				x_dataset.addElement("result").setText("fail");
				x_dataset.addElement("reason").setText("无此商品或是商品未上架");
			}
		} catch (Exception e) {
			x_dataset.addElement("result").setText("error");
			x_dataset.addElement("reason").setText("系统内部错误");
			System.out.println("***" + e.toString());
			logger.info("MobileAction_product error :{}", e.toString());
		}
		writer.write(document);
		writer.flush();
		writer.close();
		System.out.println(out.toString());
		setXML_Result(out.toString());
		return "finish";
	}

	public String productimages() throws Exception {
		try {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			String p_productid = request.getParameter("productid");
			String p_limit = request.getParameter("limit");
			System.out.println("###" + p_productid);

			// 組織條件項目
			CommonCriteria crit = new CommonCriteria();
			crit.addEq("productId", p_productid);
			crit.addEq("type", "IMGB");
			crit.addEq("isDelete", "N");

			List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });

			// ----------------------------------
			StringWriter out = new StringWriter();
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			Element x_product;
			Element x_product_id;

			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer = new XMLWriter(out, format);
			if (images != null) {
				for (int a = 0; a < images.size(); a++) {
					Image image = images.get(a);
					x_product = x_dataset.addElement("productimage");
					x_product_id = x_product.addElement("product_id").addText(image.getProductId());
					x_product_id = x_product.addElement("image_path").addText(image.getImgFilePath());

				}
			}
			writer.write(document);
			writer.flush();
			writer.close();
			System.out.println(out.toString());
			setXML_Result(out.toString());
		} catch (Exception e) {
			System.out.println("***" + e.toString());
			logger.info("MobileAction_product error :{}", e.toString());
		}
		return "finish";
	}

	public String golisthotterm() throws Exception {
		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_hotterms;
		Element x_hotterm;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);
		try {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			String hql = "from Keyword where categoryId=?";
			Keyword kwd = (Keyword) baseMgr.queryByHql(hql, new Object[] { "0" }, 0, 1)[0];
			x_hotterms = x_dataset.addElement("hotterms");
			String[] kw = kwd.getWords();

			for (int a = 0; a < kw.length; a++) {
				x_hotterm = x_hotterms.addElement("hotterm").addText(kw[a]);
			}

			x_dataset.addElement("result").setText("success");
			x_dataset.addElement("reason").setText("成功");
		} catch (Exception e) {
			x_dataset.addElement("result").setText("error");
			x_dataset.addElement("reason").setText("系统内部错误");
			System.out.println(e.toString());
			logger.info("MobileAction_product error :{}", e.toString());
		}
		writer.write(document);
		writer.flush();
		writer.close();
		System.out.println(out.toString());
		setXML_Result(out.toString());
		return "finish";
	}

	public String listNewsAll() throws Exception {
		try {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			String p_newsid = (request.getParameter("newsid") != null ? request.getParameter("newsid") : null);
			String p_limit = (request.getParameter("limit") != null ? request.getParameter("limit") : "10");
			int p_limit_v = Integer.valueOf(p_limit).intValue();
			CommonCriteria crit = new CommonCriteria();
			SimpleDateFormat dateformat1 = new SimpleDateFormat("yyyy-MM-dd");

			if (p_newsid != null) {
				crit.addEq("id", Long.valueOf(p_newsid));
			}
			crit.addLe("startDate", new Date());
			crit.addGe("startDate", DateUtils.addYears(new Date(), -1));
			crit.addEq("isDelete", "N");
			crit.addEq("type", "MYYAODIAN");

			announcementSize = announcementService.getListSize(crit).longValue();

			pager.setCurrentPage(0);
			pager.setPageRecord(20);// defaut 20
			pager.setTotalSize((p_limit_v > announcementSize ? announcementSize : p_limit_v)); // announcementSize

			announcementList = announcementService.getList(pager.getCurrentPage() * pager.getPageRecord(), pager
					.getPageRecord(), crit, new String[] { "startDate " + orderByDate, AnnouncementService.SHOW_SEQ_SORT_CLAUSE,
					"modifyDate desc" });
			StringWriter out = new StringWriter();
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			Element x_news;
			Element x_news_id;
			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer = new XMLWriter(out, format);
			if (announcementList.size() != 0) {
				int n_size = (announcementList.size() > p_limit_v ? p_limit_v : announcementList.size());

				for (int a = 0; a < n_size; a++) {
					Announcement amnt = announcementList.get(a);
					x_news = x_dataset.addElement("news");
					if (amnt.getId() != null) {
						x_news.addElement("nid").addText(String.valueOf(amnt.getId()));
					} else {
						x_news.addElement("nid").addText("");
					}
					if (amnt.getSubject() != null) {
						x_news.addElement("subject").addText(amnt.getSubject());
					} else {
						x_news.addElement("subject").addText("");
					}
					if (amnt.getBody() != null) {
						x_news.addElement("body").addText(amnt.getBody());
					} else {
						x_news.addElement("body").addText("");
					}
					if (amnt.getCreateDate() != null) {
						x_news.addElement("createdate").addText(dateformat1.format(amnt.getCreateDate()));
					} else {
						x_news.addElement("createdate").addText("");
					}
					if (amnt.getStartDate() != null) {
						x_news.addElement("startdate").addText(dateformat1.format(amnt.getStartDate()));
					} else {
						x_news.addElement("startdate").addText("");
					}
					if (amnt.getEndDate() != null) {
						x_news.addElement("enddate").addText(dateformat1.format(amnt.getEndDate()));
					} else {
						x_news.addElement("enddate").addText("");
					}

				}
			}
			writer.write(document);
			writer.flush();
			writer.close();
			System.out.println(out.toString());
			setXML_Result(out.toString());
		} catch (Exception e) {
			System.out.println(e.toString());
			logger.info("MobileAction_product error :{}", e.toString());
		}
		return "finish";
	}

	public String showNews() throws Exception {
		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_news;
		Element x_news_id;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);
		String anncontent = "";
		String startDateParam;
		String endDateParam;
		String createDateParam;
		String annNameParam;

		try {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			String annId = (request.getParameter("newsid") != null ? request.getParameter("newsid") : null);
			Announcement amnt = announcementService.getVisibleAnnouncementById(annId);

			if (amnt == null) {
				x_dataset.addElement("result").setText("fail");
				x_dataset.addElement("reason").setText("无此讯息");
			} else {
				if ("N".equals(amnt.getIsDelete())) {
					DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					createDateParam = df.format(amnt.getCreateDate());
					startDateParam = df.format(amnt.getStartDate());
					endDateParam = df.format(amnt.getEndDate());
					annNameParam = amnt.getSubject();
					if (StringUtils.isNotBlank(amnt.getBody())) {
						anncontent = amnt.getBody();
					}
					x_news = x_dataset.addElement("news");
					if (amnt.getId() != null) {
						x_news.addElement("nid").addText(String.valueOf(amnt.getId()));
					} else {
						x_news.addElement("nid").addText("");
					}
					if (amnt.getSubject() != null) {
						x_news.addElement("subject").addText(amnt.getSubject());
					} else {
						x_news.addElement("subject").addText("");
					}
					if (amnt.getBody() != null) {
						x_news.addElement("body").addCDATA(anncontent);
					} else {
						x_news.addElement("body").addText("");
					}
					if (amnt.getCreateDate() != null) {
						x_news.addElement("createdate").addText(createDateParam);
					} else {
						x_news.addElement("createdate").addText("");
					}
					if (amnt.getStartDate() != null) {
						x_news.addElement("startdate").addText(startDateParam);
					} else {
						x_news.addElement("startdate").addText("");
					}
					if (amnt.getEndDate() != null) {
						x_news.addElement("enddate").addText(endDateParam);
					} else {
						x_news.addElement("enddate").addText("");
					}

				} else {
					x_dataset.addElement("result").setText("fail");
					x_dataset.addElement("reason").setText("无此讯息");
				}
			}
		} catch (Exception e) {
			System.out.println(e.toString());
			logger.info("MobileAction_product error :{}", e.toString());
			x_dataset.addElement("result").setText("fail");
			x_dataset.addElement("reason").setText("系统错误");
		}
		writer.write(document);
		writer.flush();
		writer.close();
		System.out.println(out.toString());
		setXML_Result(out.toString());
		return "finish";
	}

	public String login() throws Exception {
		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_login;
		Element x_login_result;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);
		x_login = x_dataset.addElement("login");
		System.out.println("***" + loginID + "-" + pwd);
		try {
			loginresult = "";
			if (StringUtils.isBlank(loginID) || StringUtils.isBlank(pwd)) { // login error
				x_login_result = x_login.addElement("result").addText("fail");
				x_login_result = x_login.addElement("reason").addText("登入数据不完全，无法登入");
				writer.write(document);
				writer.flush();
				writer.close();
				System.out.println(out.toString());
				setXML_Result(out.toString());
				return "finish";
			}
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			// get ip
			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			String clientIp = StringUtils.isBlank(host) ? "" : (host.length() > 100 ? host.substring(0, 100) : host);

			System.out.println("***" + memberService);
			if (isNumeric(loginID)) {
				member = memberService.getMemberByMobile(loginID);
			} else if (loginID.contains("@")) {
				member = memberService.getMemberByEmail(loginID);
			} else {
				member = memberService.getMemberByLoginId(loginID);
			}
			if (null == member) {
				loginresult = "unfind"; // 帐号不存在
				x_login_result = x_login.addElement("result").addText("fail");
				x_login_result = x_login.addElement("reason").addText("帐号不存在");
				writer.write(document);
				writer.flush();
				writer.close();
				System.out.println(out.toString());
				setXML_Result(out.toString());
				return "finish";
			} // else if (member.getStatus().equals("10")) {

			if ("nonmember".equals(member.getApplySource()) && null == member.getActivateExpireDate()) {
				loginresult = "nonmember"; // 非会员
				x_login_result = x_login.addElement("result").addText("fail");
				x_login_result = x_login.addElement("reason").addText("非会员");
				writer.write(document);
				writer.flush();
				writer.close();
				System.out.println(out.toString());
				setXML_Result(out.toString());
				return "finish";
			}

			UserData userData = new UserData(request, response);
			/*
			 * if (errTimes > 3 && !checkCode(userData.getImageValid(), ccode)) { loginresult = "code_error"; // 验证码错误
			 * memberService.saveFrontendLoginHistory(member.getLoginId()); errTimes =
			 * memberService.getLoginHistorySize(member.getLoginId(), null, null); // if
			 * (memberService.getLoginHistorySize(member.getLoginId(), null, null) > LOGINERROR_TIMES) { //
			 * memberService.saveFrontendLoginBlackList(member.getLoginId()); // }
			 * x_login_result=x_login.addElement("result").addText("fail");
			 * x_login_result=x_login.addElement("reason").addText("验证码错误"); writer.write(document); writer.flush();
			 * writer.close(); System.out.println(out.toString()); setXML_Result(out.toString()); return "finish"; }
			 */

			if (null == memberService.loginPwdCheck(pwd, member)) {
				System.out.println("密码错误");
				loginresult = "pwd_error"; // 密码错误
				memberService.saveFrontendLoginHistory(member, clientIp, "2");
				errTimes = memberService.getLoginHistorySize(member.getLoginId(), null, null);
				// if (errTimes > 10) {
				// return "forgetpwd";
				// memberService.saveFrontendLoginBlackList(member.getLoginId());
				// }
				x_login_result = x_login.addElement("result").addText("fail");
				x_login_result = x_login.addElement("reason").addText("密码错误");
				writer.write(document);
				writer.flush();
				writer.close();
				System.out.println(out.toString());
				setXML_Result(out.toString());
				return "finish";
			}
			if (member.getActiveDate() == null) { // 帐号未激活
				System.out.println("帐号未激活");
				x_login_result = x_login.addElement("result").addText("fail");
				x_login_result = x_login.addElement("reason").addText("帐号未激活");
				writer.write(document);
				writer.flush();
				writer.close();
				System.out.println(out.toString());
				setXML_Result(out.toString());
				return "finish";
				/*
				 * if (StringUtils.isNotBlank(member.getActivateToken())) { loginID = member.getLoginId(); mail =
				 * member.getEmail(); return "waitactivate"; } else { actionResult = "fromlogin"; loginID = member.getLoginId();
				 * mobile = member.getMobile(); return "waitmobileactive"; }
				 */
			}

			LoginHistory loginHistory = memberService.getLastLoginHistory(member.getLoginId());
			if (null != loginHistory) {
				member.setLastLoginTime(loginHistory.getLoginTime());
				memberService.update(member);
				memberService.deleteLoginHistory(member.getLoginId());
			}
			memberService.saveFrontendLoginHistory(member, clientIp);
			memberService.checkLoginBonus(member, request.getServerName(), userData.getApplySource());
			userData.setLoginId(member.getLoginId());
			userData.setMemberId(member.getMemberId());

			x_login_result = x_login.addElement("result").addText("success");
			x_login_result = x_login.addElement("reason").addText("登入成功");
			writer.write(document);
			writer.flush();
			writer.close();
			System.out.println(out.toString());
			setXML_Result(out.toString());
			return "finish";
			// if (null == remember) {
			// userData.clearNickname();
			// } else {
			// userData.setNickname(loginID);
			// }
			// 检查购物车，若为空，直接产生一个
			// CartOrders cartOrders = cartOrdersService.getCart(member.getMemberId(), null);
			// if (cartOrders == null) {
			// cartOrders = cartOrdersService.createCart(member.getMemberId(), null, null, null, 0, null, null);
			// }
			// String tmpCartid = StringUtils.defaultString(userData.readRawValue("cartid"));

			// cartOrders = processMoveTmpCartToCartOrder(tmpCartid, cartOrders.getCartId(), cartOrdersService, userData);

			// 记录购物车商品数量
			// cartOrders = cartOrdersService.get(cartOrders.getCartId());
			// userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
		} catch (Exception e) {
			System.out.println(e.toString());
			logger.info("MobileAction_product error :{}", e.toString());

			x_login_result = x_login.addElement("result").addText("fail");
			x_login_result = x_login.addElement("reason").addText("内部程序错误");
			writer.write(document);
			writer.flush();
			writer.close();
			System.out.println(out.toString());
			setXML_Result(out.toString());
			return "finish";
		}

		// return "finish";
	}

	public String logout() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		userData.clearAll(); // 清除登入讯息等于登出

		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_login;
		Element x_login_result;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);
		x_login = x_dataset.addElement("logout");
		x_login_result = x_login.addElement("result").addText("success");
		x_login_result = x_login.addElement("reason").addText("成功登出");
		writer.write(document);
		writer.flush();
		writer.close();
		System.out.println(out.toString());
		setXML_Result(out.toString());
		return "finish";
	}

	public String isLogin() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_login;
		Element x_login_result;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);
		x_login = x_dataset.addElement("login");
		try {

			UserData userData = new UserData(request, response);
			// if (StringUtils.isNotBlank(userData.getNickname())) { // Nick name 尚未发现有任何效用
			// loginID = userData.getNickname();
			// nickId = loginID;
			// }
			//
			String tmp = userData.getLoginId();

			if (StringUtils.isNotBlank(tmp)) {
				member = memberService.getMemberByLoginId(tmp, request.getServerName());
				if (member == null) {
					x_login_result = x_login.addElement("islogin").addText("no");
					x_login_result = x_login.addElement("reason").addText("未登入");
					// return false;
				} else {
					x_login_result = x_login.addElement("islogin").addText("yes");
					x_login_result = x_login.addElement("reason").addText("已登入");
				}
			} else {
				x_login_result = x_login.addElement("islogin").addText("no");
				x_login_result = x_login.addElement("reason").addText("登入已过时");
				// return false;
			}

			writer.write(document);
			writer.flush();
			writer.close();
			System.out.println(out.toString());
			setXML_Result(out.toString());
			return "finish";
		} catch (Exception e) {
			System.out.println(e.toString());
			logger.info("MobileAction_product error :{}", e.toString());

			x_login_result = x_login.addElement("result").addText("no");
			x_login_result = x_login.addElement("reason").addText("内部程序错误");
			writer.write(document);
			writer.flush();
			writer.close();
			System.out.println(out.toString());
			setXML_Result(out.toString());
			return "finish";
		}
	}

	public String listwishlist() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_wishlist;
		Element x_wish;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);

		try {
			UserData userData = new UserData(request, response);
			System.out.println(" user data:" + userData.getLoginId());
			if (StringUtils.isNotBlank(userData.getLoginId())) {
				member = memberService.getMemberByLoginId(userData.getLoginId(), request.getServerName());
				System.out.println(" member:" + member.getMemberId());
				if (member != null) {
					CommonCriteria crit = new CommonCriteria();
					crit.addEq("memberId", member.getMemberId());
					crit.addEq("categoryId", null);
					crit.addNe("shelfPrice", null);
					crit.addNe("is_delete", "Y");
					viewWishList = memberService.getViewWishLists(0, -1, crit, null); // 第一阶段只做收藏商品
					// productListSize = viewWishList.size();
					// crit = new CommonCriteria();
					// crit.addEq("memberId", member.getMemberId());
					// crit.addEq("productId", null);
					// List<ViewWishList> vwlist = memberService.getViewWishLists(0, -1, crit, null);
					System.out.println("viewWishList.size():" + viewWishList.size());
					for (ViewWishList vwl : viewWishList) {

						x_wishlist = x_dataset.addElement("wishlist");
						x_wish = x_wishlist.addElement("wishlistid").addText(String.valueOf(vwl.getId()));
						x_wish = x_wishlist.addElement("productid").addText(vwl.getProductId());
						x_wish = x_wishlist.addElement("productname").addText(vwl.getProductName());
						x_wish = x_wishlist.addElement("putproductprice").addText(String.valueOf(vwl.getPutProductPrice()));

						CommonCriteria crit2 = new CommonCriteria();
						crit2.addEq("productId", vwl.getProductId());
						crit2.addEq("type", "MAIN");
						crit2.addEq("isDelete", "N");
						List<Image> images = imageservice.getList(1, 10, crit2, new String[] { "id desc" });
						int b1 = 0;
						for (Image img : images) {
							if (img.getImgFilePath().indexOf("_m75") != -1) {
								x_wish = x_wishlist.addElement("image_path").addText(img.getImgFilePath());
								b1 = 1;
							}
						}
						if (b1 == 0) {
							x_wish = x_wishlist.addElement("image_path").addText("");
						}

					}

				}
			} else {
				x_dataset.addElement("result").setText("fail");
				x_dataset.addElement("reason").setText("无登入讯息,请重新登入");
			}
		} catch (Exception e) {
			x_dataset.addElement("result").setText("error");
			x_dataset.addElement("reason").setText("系统内部错误");
			System.out.println(e.toString());
			logger.info("MobileAction_product error :{}", e.toString());
			// x_wish=x_wishlist.addElement("result").addText("no");
			// x_wish=x_wishlist.addElement("reason").addText("内部程序错误");
		}
		writer.write(document);
		writer.flush();
		writer.close();
		System.out.println(out.toString());
		setXML_Result(out.toString());
		return "finish";
	}

	public String saveWishList() throws Exception {
		// 參數輸入:productId, productPrice
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_wishlist;
		Element x_wish;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);

		try {
			UserData userData = new UserData(request, response);
			if (userData.getLoginId() != null) {
				member = memberService.getMemberByLoginId(userData.getLoginId(), request.getServerName());
				WishList entity = new WishList();
				System.out.println("viewWishList.size():" + member.getMemberId());
				if (productId != null) {
					entity.setMemberId(member.getMemberId());
					entity.setProductId(productId);
					entity.setPutProductPrice(new BigDecimal(productPrice));
					entity.setMemo("");
					entity.setIsPriceNotify("N");
					entity.setLowerPriceNotify(new BigDecimal("0.0"));
					entity.setIsRestockNotify("N");
				}
				System.out.println("qqq:" + member.getMemberId());

				if (memberService.checkWishListExist(entity)) {
					x_dataset.addElement("result").setText("fail");
					x_dataset.addElement("reason").setText("项目已存在收藏盒");

				} else {
					entity = memberService.saveWishList(entity);
					x_dataset.addElement("result").setText("success");
					x_dataset.addElement("reason").setText("新增成功");

				}
			} else {
				x_dataset.addElement("result").setText("fail");
				x_dataset.addElement("reason").setText("无登入讯息,请重新登入");
			}
		} catch (Exception e) {
			x_dataset.addElement("result").setText("error");
			x_dataset.addElement("reason").setText("系统内部错误");
			System.out.println(e.toString());
			logger.info("MobileAction_product error :{}", e.toString());
		}
		writer.write(document);
		writer.flush();
		writer.close();
		System.out.println(out.toString());
		setXML_Result(out.toString());
		return "finish";
	}

	public String deleteWishList() throws Exception {
		// 輸入參數：delIdList
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		// Element x_wishlist;
		// Element x_wish;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);
		try {
			UserData userData = new UserData(request, response);
			if (userData.getLoginId() != null) {
				if (delIdList != null) {
					String[] delList = delIdList.split(",");

					if (memberService.deleteWishList(delList)) {
						x_dataset.addElement("result").setText("success");
						x_dataset.addElement("reason").setText("删除成功");

					} else {
						x_dataset.addElement("result").setText("fail");
						x_dataset.addElement("reason").setText("删除失败");
					}
				} else {
					x_dataset.addElement("result").setText("fail");
					x_dataset.addElement("reason").setText("无登入讯息");
				}
			}
		} catch (Exception e) {
			x_dataset.addElement("result").setText("error");
			x_dataset.addElement("reason").setText("系统内部错误");
			System.out.println(e.toString());
			logger.info("MobileAction_product error :{}", e.toString());
		}
		writer.write(document);
		writer.flush();
		writer.close();
		System.out.println(out.toString());
		setXML_Result(out.toString());
		return "finish";
	}

	public String golistCart() throws Exception {
		// 取得購物車資訊，此程式參考 com.yaodian100.mall.shopping.web.CartAction reloadCart()
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_cartlist;
		Element x_cart;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);
		try {
			UserData userData = new UserData(request, response);

			if (StringUtils.isNotBlank(userData.getLoginId())) {

				String tmpCartId = StringUtils.defaultString(userData.readRawValue("cartid"));
				String memberId = StringUtils.defaultString(userData.getMemberId());

				// 瀏覽器裏已有cookie就放入tmpCartid
				// viewEcCartList = null;
				// 帳號登入
				// System.out.println("####"+memberId);
				if (StringUtils.isNotBlank(memberId)) { // 只有帳號登入才能取得購物車資訊
					cartOrders = cartOrdersService.getCart(memberId, null);
				}

				/*
				 * if (null == cartOrders) { cartOrders = new CartOrders(); } else { Map<String, String> optional = new
				 * HashMap<String, String>(); optional.put("domain", request.getServerName()); optional.put("cookie",
				 * userData.getApplySource()); cartOrders = cartOrdersService.calculateCart(cartOrders, optional); }
				 */

				// x_dataset.addElement("cart_id").setText(cartOrders.getCartId());
				if (cartOrders != null) {
					Map<String, String> optional = new HashMap<String, String>();
					optional.put("domain", request.getServerName());
					optional.put("cookie", userData.getApplySource());
					cartOrders = cartOrdersService.calculateCart(cartOrders, optional); // 每次從新計算shopping cart的金額

					cartOrderProductList = cartOrders.getCartOrderProducts();
					CommonCriteria crit = new CommonCriteria();

					for (CartOrderProduct cartOrderProduct : cartOrderProductList) {
						tlpList = timeLimitSaleService.findTimeLimitSale(cartOrders.getCartOrderProducts());

						x_cartlist = x_dataset.addElement("shoppingcart");
						x_cart = x_cartlist.addElement("cart_id").addText(cartOrders.getCartId());
						x_cart = x_cartlist.addElement("product_id").addText(cartOrderProduct.getProdId());
						x_cart = x_cartlist.addElement("cart_order_product_id").addText(
								String.valueOf(cartOrderProduct.getCartOrderProdId()));
						x_cart = x_cartlist.addElement("campaign_id").addText(cartOrderProduct.getCampaignId());
						x_cart = x_cartlist.addElement("product_name").addText(cartOrderProduct.getProdName());
						x_cart = x_cartlist.addElement("campaign_name").addText(cartOrderProduct.getCampaignName());
						x_cart = x_cartlist.addElement("category_Path").addText(cartOrderProduct.getCategoryPath());

						int c = 0;
						if (tlpList != null) {
							for (int b = 0; b < tlpList.size(); b++) {
								if (tlpList.get(b).equals(cartOrderProduct.getProdId())) {
									x_cart = x_cartlist.addElement("promote_name").addText("timelimitsales");
									c = 1;
								}
							}
						}
						if (c == 0) {
							x_cart = x_cartlist.addElement("promote_name").addText("");
						}
						x_cart = x_cartlist.addElement("product_spec_id").addText(cartOrderProduct.getProdSpecId());
						x_cart = x_cartlist.addElement("product_spec_name").addText(cartOrderProduct.getProdSpecName());
						x_cart = x_cartlist.addElement("product_Tp").addText(cartOrderProduct.getProdTp());

						x_cart = x_cartlist.addElement("discount").addText(String.valueOf(cartOrderProduct.getDiscount()));
						x_cart = x_cartlist.addElement("qty").addText(String.valueOf(cartOrderProduct.getQty()));
						x_cart = x_cartlist.addElement("unit_price").addText(String.valueOf(cartOrderProduct.getUnitPrice()));
						x_cart = x_cartlist.addElement("total_price").addText(String.valueOf(cartOrderProduct.getTotalPrice()));

						crit.addEq("productId", cartOrderProduct.getProdId());
						crit.addEq("type", "MAIN");
						crit.addEq("isDelete", "N");
						List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });
						int b1 = 0;
						for (Image img : images) {
							if (img.getImgFilePath().indexOf("_m75") != -1) {
								x_cart = x_cartlist.addElement("image_path").addText(img.getImgFilePath());
								b1 = 1;
							}
						}
						if (b1 == 0) {
							x_cart = x_cartlist.addElement("image_path").addText("");
						}

					}
				}

				// fromProduct = StringUtils.defaultString(userData.readRawValue("fromProduct"));
				// fromCategory = StringUtils.defaultString(userData.readRawValue("fromCategory"));
				// 记录购物车商品数量
				logger.info("cartOrders.getProductSum():{}", cartOrders.getProductSum());
				// userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));

				// 限時搶購商品回传代码
				/**
				 * public static String NONMEMBER = "0"; public static String EVER_BUY = "1"; public static String OK = "2";
				 * public static String MULTIPLE_PROD = "3";
				 */
				tlpCode = timeLimitSaleService.canBuy(cartOrders.getCartOrderProducts(), memberId);
				if (StringUtils.equals("0", tlpCode)) {
					x_dataset.addElement("timelimitstatous").addText("NONMEMBER");
				} else if (StringUtils.equals("1", tlpCode)) {
					x_dataset.addElement("timelimitstatous").addText("EVER_BUY");
				} else if (StringUtils.equals("2", tlpCode)) {
					x_dataset.addElement("timelimitstatous").addText("OK");
				} else if (StringUtils.equals("3", tlpCode)) {
					x_dataset.addElement("timelimitstatus").addText("MULTIPLE_PROD");
				}
			} else {
				x_dataset.addElement("result").setText("fail");
				x_dataset.addElement("reason").setText("无登入讯息");
			}
		} catch (Exception e) {
			x_dataset.addElement("result").setText("error");
			x_dataset.addElement("reason").setText("系统内部错误");
			System.out.println(e.toString());
			logger.info("MobileAction_product error :{}", e.toString());
		}
		writer.write(document);
		writer.flush();
		writer.close();
		System.out.println(out.toString());
		setXML_Result(out.toString());
		return "finish";
	}

	/*
	 * Request输入参数 itemNo - 商品 ID specNo - 商品属性 ID qty - 数量 categoryPath - 商品分类 ptype - 商品型态
	 */
	public String addCart() throws Exception { // 新增商品项目至购物车 --运作中
		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_cartlist;
		Element x_cart;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);
		Long opid = Long.valueOf("0");
		Integer amnt = 0;

		try {
			System.out.println("***Start Process***");
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);

			UserData userData = new UserData(request, response);

			System.out.println(itemNo[0]);
			System.out.println(specNo[0]);
			System.out.println(qty[0]);
			System.out.println(categoryPath[0]);
			System.out.println(ptype[0]);

			// userData.writeRawValue(UserData.NAME_YAODIAN100_TL_RS, ServerValue.getFrontContextPath() +
			// "/shopping/cart.do");
			// 瀏覽器裏已有cookie就放入tmpCartid
			// String tmpCartid = StringUtils.defaultString(userData.readRawValue("cartid"));
			String memberId = StringUtils.defaultString(userData.getMemberId());

			// viewEcCartList = null;

			// ADDONS 改為只放addon product id
			List<String> addOnProductIds = new ArrayList<String>();
			String[] addOnsSplit = null;
			if (addOns != null) {
				addOns = addOns.replaceAll("\"", "");
				addOnsSplit = addOns.split(",");
				for (String str : addOnsSplit) {
					addOnProductIds.add(str);
				}
			}

			// 帳號登入
			if (null != userData && StringUtils.isNotBlank(memberId)) {

				member = memberService.get(memberId);

				if (null != member) {
					cartOrders = cartOrdersService.getCart(member.getMemberId(), null);
					logger.info("cartOrders:{}", cartOrders);

					if (null == cartOrders) { // 已登入且會員從未加入過購物車
						cartOrders = cartOrdersService.createCartForStep1(memberId, null, null, null, 0, null, null); // 新增一個購物車
					}
					boolean isItemExist = false;
					// CommonCriteria crit = new CommonCriteria();
					// crit.addEq("productId", product.getProductId());
					// List inventories = productService.getSpecificationInventory(crit); // 检查是否有库存

					if (itemNo != null && !"6".equals(ptype[0])) {
						// System.out.println("###4.5");
						for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {

							if (cop.getProdSpecId().equals(specNo[0])) {
								isItemExist = true;
								opid = cop.getCartOrderProdId();
								amnt = cop.getQty();
								break;
							}
						}
					}

					if (!isItemExist) { // 如果商品未存在在購物車中，執行商品加入動作
						if (null != itemNo) {
							String categoryId = NumberUtils.isNumber(categoryPath[0]) ? categoryPath[0] : StringUtils
									.parseNumber(categoryPath[0]);
							if (!"6".equals(ptype[0])) {
								cartOrders = cartOrdersService.addProductForStep1(member.getMemberId(), cartOrders.getCartId(),
										itemNo[0], null, Long.valueOf(specNo[0]), Integer.valueOf(qty[0]), categoryId, addOnProductIds);
							} else {
								cartOrders = cartOrdersService.addProductForStep1(member.getMemberId(), cartOrders.getCartId(),
										itemNo[0], addOnProductIds, Long.valueOf(specNo[0]), Integer.valueOf(qty[0]), categoryId, null);
							}
							// 记录商品類別cookie
							// userData.writeRawValue("fromProduct",
							// categoryService.get(Long.parseLong(categoryId)).getCategoryPath().split("/")[0]);
						}
						// if (StringUtils.isNotBlank(cmpUuid)) { //滿額購暫時不考慮納入mobile購買
						// cartOrders = addPromotionProduct(cartOrders, cmpUuid);
						// }
						x_dataset.addElement("result").setText("success");
						x_dataset.addElement("reason").setText("新增商品成功");
					} else { // 如果商品已存在在購物車中，執行商品數量修改
						if (opid != 0) {
							String hql = "from SpecificationInventory where specId=?";
							// Integer selectProdQty = Integer.parseInt(prodQty);
							CartOrderProduct copCurrent = (CartOrderProduct) baseMgr.get(CartOrderProduct.class, opid);
							SpecificationInventory si = (SpecificationInventory) baseMgr.queryByHql(hql, new Object[] { copCurrent
									.getProdSpecId() }, 0, 1)[0];
							Integer inventory = si.getInventory();
							Product product = (Product) baseMgr.get(Product.class, si.getProductId());
							if ((inventory > 0) || (amnt > Integer.valueOf(qty[0]))) { // 檢查庫存
								// 所选属性库存不足
								Integer am = 0;

								if (Integer.valueOf(qty[0]) > inventory) {
									am = inventory;
								} else {
									am = Integer.valueOf(qty[0]);
								}
								for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
									if (cop.getProdSpecId().equals(specNo[0])) {
										cop.setQty(am);

										for (CartOrderProductDetail copd : cop.getDetails()) {
											if (copd.getProdSpecId().equals(specNo[0])) {
												// System.out.println("###-->更新"+copd.getProdSpecId());
												// copd.setProdSpecId(cop.getProdSpecId());
												// copd.setProdSpecName(cop.getProdSpecName());
												copd.setQty(cop.getQty());
												baseMgr.update(copd);
												break;
											}
										}

										baseMgr.update(cop);
										break;
									}
								}
								Map<String, String> optional = new HashMap<String, String>();
								// optional.put("domain", request.getServerName());
								// optional.put("cookie", userData.getApplySource());
								cartOrders = cartOrdersService.calculateCart(cartOrders, optional); // 從新計算購物車
								/*
								 * for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) { if
								 * (cop.getProdSpecId().equals(specNo[0])) { System.out.println("-->"+cop.getQty());
								 * System.out.println("-->"+cop.getTotalPrice()); break; } }
								 */
								cartOrdersService.update(cartOrders);
								x_dataset.addElement("result").setText("success");
								x_dataset.addElement("reason").setText("数量更新");
							} else {
								x_dataset.addElement("result").setText("fail");
								x_dataset.addElement("reason").setText("已无库存");
							}

						} else {
							x_dataset.addElement("result").setText("fail");
							x_dataset.addElement("reason").setText("新增商品已存在");
						}
					}
				} else {
					x_dataset.addElement("result").setText("fail");
					x_dataset.addElement("reason").setText("无登入讯息");
				}
			} else {
				x_dataset.addElement("result").setText("fail");
				x_dataset.addElement("reason").setText("未登入");
			}
			// 记录购物车商品数量
			// cartOrders = cartOrdersService.get(cartOrders.getCartId());
			// userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
			// addCartResult = "success";

		} catch (Exception e) {
			// addCartResult = "failure";
			// e.printStackTrace();
			// throw e;
			x_dataset.addElement("result").setText("error");
			x_dataset.addElement("reason").setText("系统内部错误");
			System.out.println(e.toString());
			logger.info("MobileAction_product error :{}", e.toString());
		}
		writer.write(document);
		writer.flush();
		writer.close();
		System.out.println(out.toString());
		setXML_Result(out.toString());
		return "finish";
	}

	CartOrders addPromotionProduct(CartOrders cartOrders, String cmpUuid) throws Exception {
		if (StringUtils.isNotBlank(cmpUuid)) {
			boolean hasFive = false;
			for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
				if (cop.getProdTp().equals("5")) {
					hasFive = true;
					break;
				}
			}
			if (!hasFive) {
				cartOrders = cartOrdersService.addPromoteProduct(cartOrders, cmpUuid, "5");
				cartOrders = cartOrdersService.save(cartOrders);
			}
		}
		return cartOrders;
	}

	public String delCart() throws Exception { // 删除购物车商品项目 --运作中
		StringWriter out = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element x_dataset = document.addElement("dataset");
		Element x_cartlist;
		Element x_cart;
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);

		try {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			UserData userData = new UserData(request, response);
			String flag = "error";
			// CommonCriteria crit = new CommonCriteria();

			// String memberId = StringUtils.defaultString(userData.getMemberId());
			CartOrders cart = cartOrdersService.get(cartId);

			// cartOrders = cartOrdersService.getCart(memberId, null);

			// Iterator<CartOrderProduct> it = cartOrders.getCartOrderProducts().iterator();

			// while (it.hasNext()) {
			// cartOrderProductList = cartOrders.getCartOrderProducts();
			for (CartOrderProduct cop : cart.getCartOrderProducts()) {
				// CartOrderProduct cop = it.next();
				System.out.println(">>>***" + cop.getCartOrderProdId());
				System.out.println(">>>***" + cop.getProdId());
				if (cop.getCartOrderProdId().equals(Long.valueOf(delCartProdId))) {
					System.out.println("###***" + cop.getDetails().size());
					for (CartOrderProductDetail copd : cop.getDetails()) {
						System.out.println("###1" + copd);
						baseMgr.delete(copd);
					}
					System.out.println("###2");
					baseMgr.delete(cop);
					// it.remove();
					// flag = "success";
					break;
				}
			}
			// cartordersService.save(cart);
			// Map<String, String> optional = new HashMap<String, String>();
			// optional.put("domain", request.getServerName());
			// optional.put("cookie", userData.getApplySource());
			// cartOrders = cartOrdersService.calculateCart(cart, optional);
			// 记录购物车商品数量
			// userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
			// actionResult = flag;
			x_dataset.addElement("result").setText("success");
			x_dataset.addElement("reason").setText("项目删除成功");
		} catch (Exception e) {
			x_dataset.addElement("result").setText("error");
			x_dataset.addElement("reason").setText("系统内部错误");
			System.out.println(e.toString());
			logger.info("MobileAction_product error :{}", e.toString());
		}
		writer.write(document);
		writer.flush();
		writer.close();
		System.out.println(out.toString());
		setXML_Result(out.toString());
		return "finish";
	}

	Map<String, String> weightMap(CartOrders cartOrders) throws Exception {
		cartOrderProductList = cartOrders.getCartOrderProducts();
		cartOrderProductDetailList = new ArrayList<CartOrderProductDetail>();
		Shelf shelf = null;
		for (CartOrderProduct product : cartOrderProductList) {
			for (CartOrderProductDetail detail : product.getDetails()) {

				if (StringUtils.contains("015", detail.getDetailTp())) {
					shelf = shelfService.getActiveShelfByProductId(detail.getProdId());
					if (null != shelf && detail.getQty() > 0) {
						cartOrderProductDetailList.add(detail);
					}
				} else if (StringUtils.contains("2346", detail.getDetailTp())) {
					cartOrderProductDetailList.add(detail);
				}
			}
		}
		Map<String, String> weightMap = cartOrdersService.showProductWeight(cartOrderProductDetailList);
		return weightMap;
	}

	private boolean isNumeric(String str) {
		for (int i = 0; i < str.length(); i++) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	private boolean checkCode(String imageId, String inputCode) {
		ImageValid imageValid = new ImageValid();
		imageValid.setId(imageId);
		imageValid.setValidData(inputCode);
		try {
			memberService.isImageValid(imageValid);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	@Override
	public void prepare() throws Exception {
		if (null == pager) {
			pager = new SimplePager(1);
		}
	}

	public String getXML_Result() {
		return XML_Result;
	}

	public void setXML_Result(String xMLResult) {
		XML_Result = xMLResult;
	}

	public ProductService getProductservice() {
		return productservice;
	}

	public void setProductservice(ProductService productservice) {
		this.productservice = productservice;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public String getLoginID() {
		return loginID;
	}

	public void setLoginID(String loginID) {
		this.loginID = loginID;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}

	public String getProductPrice() {
		return productPrice;
	}

	public void setProductPrice(String productPrice) {
		this.productPrice = productPrice;
	}

	public String getDelIdList() {
		return delIdList;
	}

	public void setDelIdList(String delIdList) {
		this.delIdList = delIdList;
	}

	public String[] getSpecNo() {
		return specNo;
	}

	public void setSpecNo(String[] specNo) {
		this.specNo = specNo;
	}

	public String[] getQty() {
		return qty;
	}

	public void setQty(String[] qty) {
		this.qty = qty;
	}

	public String[] getCategoryPath() {
		return categoryPath;
	}

	public void setCategoryPath(String[] categoryPath) {
		this.categoryPath = categoryPath;
	}

	public String[] getItemNo() {
		return itemNo;
	}

	public void setItemNo(String[] itemNo) {
		this.itemNo = itemNo;
	}

	public String[] getPtype() {
		return ptype;
	}

	public void setPtype(String[] ptype) {
		this.ptype = ptype;
	}

	public String getDelCartProdId() {
		return delCartProdId;
	}

	public void setDelCartProdId(String delCartProdId) {
		this.delCartProdId = delCartProdId;
	}

	public String getCartId() {
		return cartId;
	}

	public void setCartId(String cartId) {
		this.cartId = cartId;
	}

}
